package cn.iocoder.yudao.module.lowcode.service.magicapi;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.lowcode.controller.admin.generic.vo.GenericTableConfigRespVO;
import cn.iocoder.yudao.module.lowcode.core.util.MagicApiDataTypeUtil;
import cn.iocoder.yudao.module.lowcode.dal.dataobject.datasource.LowcodeDataSourceConfigDO;
import cn.iocoder.yudao.module.lowcode.dal.dataobject.magicapi.MagicApiFile;
import cn.iocoder.yudao.module.lowcode.dal.dataobject.magicapi.MagicApiFileDO;
import cn.iocoder.yudao.module.lowcode.dal.dataobject.magicapi.MagicApiGroup;
import cn.iocoder.yudao.module.lowcode.dal.dataobject.magicapi.MagicApiItem;
import cn.iocoder.yudao.module.lowcode.dal.mysql.magicapi.MagicApiFileMapper;
import cn.iocoder.yudao.module.lowcode.service.datasource.LowcodeDataSourceConfigService;
import cn.iocoder.yudao.module.lowcode.service.generic.GenericTableService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.hutool.core.text.NamingCase.toCamelCase;
import static cn.hutool.core.text.NamingCase.toUnderlineCase;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.lowcode.enums.ErrorCodeConstants.DATASOURCE_CONFIG_NOT_EXISTS;

/**
 * Magic API CRUD 接口生成服务
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class MagicApiCrudService {

    /**
     * 需要排除的系统字段集合
     * 可以根据实际需求调整
     */
    private static final Set<String> SYSTEM_FIELDS = new HashSet<>(Arrays.asList(
        "creator", "create_time", "createTime",
        "updater", "update_time", "updateTime", 
        "deleted", "tenant_id", "tenantId"
    ));

    /**
     * dev分组的固定ID，避免重复创建
     * 使用固定ID确保重启后仍能识别为同一个分组
     */
    private static final String DEV_GROUP_ID = "auto-generated-dev-group-001";

    @Resource
    private MagicApiFileMapper magicApiFileMapper;
    
    @Resource
    private GenericTableService genericTableService;
    
    @Resource
    private LowcodeDataSourceConfigService dataSourceConfigService;

    /**
     * 基于表配置生成 Magic API CRUD 接口
     *
     * @param tableName 表名
     * @param dataSourceId 数据源ID
     * @return 生成的接口数量
     */
    @TenantIgnore
    public Integer generateCrudInterfaces(String tableName, Long dataSourceId) {
        // 1. 获取表配置信息
        GenericTableConfigRespVO tableConfig = genericTableService.getTableConfig(tableName, dataSourceId);
        
        // 2. 获取数据源配置
        LowcodeDataSourceConfigDO dataSource = dataSourceConfigService.getDataSourceConfig(dataSourceId);
        if (dataSource == null) {
            throw exception(DATASOURCE_CONFIG_NOT_EXISTS);
        }
        
        // 3. 生成接口文件列表
        List<MagicApiFileDO> apiFiles = createMagicApiCrudFiles(tableName, tableConfig, dataSource);
        
        // 4. 先删除现有接口
        String groupPath = generateGroupPath(tableName, tableConfig.getTableComment());
        log.info("[generateCrudInterfaces] 删除现有接口: groupPath={}", groupPath);
        int deletedCount = magicApiFileMapper.deleteByPathPrefix(groupPath);
        log.info("[generateCrudInterfaces] 删除了 {} 个现有接口", deletedCount);
        
        // 5. 批量插入新接口
        log.info("[generateCrudInterfaces] 准备插入 {} 个新接口", apiFiles.size());
        if (!apiFiles.isEmpty()) {
            // 打印要插入的文件信息
            for (int i = 0; i < apiFiles.size(); i++) {
                MagicApiFileDO file = apiFiles.get(i);
                log.info("[generateCrudInterfaces] 文件{}: path={}, contentLength={}", 
                        i + 1, file.getFilePath(), 
                        file.getFileContent() != null ? file.getFileContent().length() : 0);
            }
            
            try {
                magicApiFileMapper.insertBatch(apiFiles);
                log.info("[generateCrudInterfaces] 批量插入完成");
                
                // 验证插入结果 - 查询刚插入的记录
                List<MagicApiFileDO> insertedFiles = magicApiFileMapper.selectList(null);
                log.info("[generateCrudInterfaces] 插入后数据库总记录数: {}", insertedFiles.size());
                
                // 检查是否包含我们刚插入的记录
                for (MagicApiFileDO apiFile : apiFiles) {
                    boolean found = insertedFiles.stream()
                            .anyMatch(f -> apiFile.getFilePath().equals(f.getFilePath()));
                    log.info("[generateCrudInterfaces] 验证插入: {} -> {}", 
                            apiFile.getFilePath(), found ? "存在" : "缺失");
                }
                
            } catch (Exception e) {
                log.error("[generateCrudInterfaces] 批量插入失败", e);
                throw e;
            }
        }
        
        log.info("[generateCrudInterfaces] 为表 {} 生成 Magic API 接口成功，共 {} 个", tableName, apiFiles.size());
        
        return apiFiles.size();
    }

    /**
     * 删除表对应的所有 Magic API 接口
     *
     * @param tableName 表名
     * @param tableComment 表注释
     * @return 删除的接口数量
     */
    @TenantIgnore
    public Integer deleteCrudInterfaces(String tableName, String tableComment) {
        String groupPath = generateGroupPath(tableName, tableComment);
        int deleteCount = magicApiFileMapper.deleteByPathPrefix(groupPath);
        
        log.info("[deleteCrudInterfaces] 删除表 {} 的 Magic API 接口，共 {} 个", tableName, deleteCount);
        
        return deleteCount;
    }
    
    /**
     * 查询所有 Magic API 文件记录（用于调试）
     */
    @TenantIgnore
    public List<Map<String, Object>> queryMagicApiFiles() {
        // 使用原生SQL查询，返回Map格式便于调试
        return magicApiFileMapper.selectMaps(null);
    }
    
    /**
     * 测试单条记录插入
     */
    @TenantIgnore
    public int testSingleInsert(MagicApiFileDO testFile) {
        log.info("[testSingleInsert] 测试插入单条记录: path={}", testFile.getFilePath());
        
        try {
            int result = magicApiFileMapper.insert(testFile);
            log.info("[testSingleInsert] 插入结果: {}", result);
            return result;
        } catch (Exception e) {
            log.error("[testSingleInsert] 插入失败", e);
            throw e;
        }
    }

    /**
     * 创建 Magic API CRUD 文件列表
     */
    private List<MagicApiFileDO> createMagicApiCrudFiles(String tableName, GenericTableConfigRespVO tableConfig, 
                                                         LowcodeDataSourceConfigDO dataSource) {
        List<MagicApiFileDO> apiFiles = new ArrayList<>();
        
        String dataSourceName = dataSource.getName();
        // 根据数据源ID和名称生成正确的数据源调用格式
        String dataSourceCall = generateDataSourceCall(dataSource.getId(), dataSourceName);
        String tableComment = StrUtil.isNotEmpty(tableConfig.getTableComment()) ? tableConfig.getTableComment() : tableName;
        String groupPath = generateGroupPath(tableName, tableComment);
        
        // 1. 获取或创建dev分组ID（不重复创建dev目录）
        String devGroupId = getOrCreateDevGroupId();
        
        // 2. 确保dev目录存在（只在首次创建时）
        ensureDevGroupExists(apiFiles, devGroupId);
        
        // 3. 创建表分组目录（使用表名作为path，表注释作为显示名称）
        String comment = StrUtil.isNotEmpty(tableComment) ? tableComment : tableName;
        MagicApiGroup tableGroup = createMagicGroup(comment, "/" + tableName, devGroupId);
        String groupId = tableGroup.getId();
        
        // 创建表分组目录文件
        apiFiles.add(createApiFile(groupPath, "this is directory"));
        
        // 创建表分组配置文件
        apiFiles.add(createApiFile(groupPath + "group.json", JSONObject.toJSONString(tableGroup)));
        
        // 3. 获取主键字段和列信息
        String primaryKey = getPrimaryKey(tableConfig);
        List<GenericTableConfigRespVO.GenericTableColumnConfig> columns = tableConfig.getColumns();
        
        // 4. 生成完整的 CRUD 接口（使用正确的格式）
        // 查询接口
        apiFiles.add(createApiFile(
            groupPath + "查询.ms",
            createQueryInterface(groupId, dataSourceCall, tableName, columns, dataSourceName)
        ));
        
        // 分页查询接口
        apiFiles.add(createApiFile(
            groupPath + "分页.ms",
            createPageInterface(groupId, dataSourceCall, tableName, columns, dataSourceName)
        ));
        
        // 新增接口
        apiFiles.add(createApiFile(
            groupPath + "新增.ms",
            createInsertInterface(groupId, dataSourceCall, tableName, columns)
        ));
        
        // 修改接口
        apiFiles.add(createApiFile(
            groupPath + "修改.ms",
            createUpdateInterface(groupId, dataSourceCall, tableName, primaryKey, columns)
        ));
        
        // 单个ID逻辑删除接口
        apiFiles.add(createApiFile(
            groupPath + "删除.ms",
            createSingleLogicDeleteInterface(groupId, dataSourceCall, tableName, primaryKey)
        ));
        
        // 批量逻辑删除接口
        apiFiles.add(createApiFile(
            groupPath + "批量删除.ms",
            createBatchLogicDeleteInterface(groupId, dataSourceCall, tableName, primaryKey)
        ));
        
        // 单个ID物理删除接口
        apiFiles.add(createApiFile(
            groupPath + "物理删除.ms",
            createSinglePhysicalDeleteInterface(groupId, dataSourceCall, tableName, primaryKey)
        ));
        
        // 批量物理删除接口
        apiFiles.add(createApiFile(
            groupPath + "批量物理删除.ms",
            createBatchPhysicalDeleteInterface(groupId, dataSourceCall, tableName, primaryKey)
        ));
        
        // Excel导出接口
        apiFiles.add(createApiFile(
            groupPath + "导出.ms",
            createExcelExportInterface(groupId, dataSourceCall, tableName, columns, tableComment)
        ));
        
        return apiFiles;
    }


    /**
     * 创建 Magic API 文件对象
     */
    private MagicApiFileDO createApiFile(String filePath, String content) {
        MagicApiFileDO apiFile = new MagicApiFileDO();
        apiFile.setFilePath(filePath);
        apiFile.setFileContent(content);
        return apiFile;
    }

    /**
     * 生成分组路径
     * 路径结构：magic-api/api/dev/表名/
     */
    private String generateGroupPath(String tableName, String tableComment) {
        return "magic-api/api/dev/" + tableName + "/";
    }

    /**
     * 创建 Magic API 分组
     */
    private MagicApiGroup createMagicGroup(String groupName, String path, String parentId) {
        MagicApiGroup group = new MagicApiGroup();
        
        // 按照您提供的正确格式设置字段
        group.setCreateBy("admin");
        group.setCreateTime(DateTime.now().getTime());
        group.setId(IdUtil.simpleUUID());
        group.setName(groupName);
        group.setOptions(new String[]{});
        group.setParentId(parentId);
        group.setPath(path);
        group.setPaths(new String[]{});
        group.setProperties(new java.util.HashMap<>()); // 确保序列化为 {}
        group.setType("api");
        group.setUpdateTime(null);
        
        return group;
    }

    /**
     * 生成数据源调用格式
     * 数据源ID为0时使用 db
     * 其他数据源使用 db['数据源名称']
     */
    private String generateDataSourceCall(Long dataSourceId, String dataSourceName) {
        if (dataSourceId == null || dataSourceId == 0L) {
            return "db";
        } else {
            return "db['" + dataSourceName + "']";
        }
    }

    /**
     * 获取或创建dev分组ID
     * 检查dev目录是否已存在，如果不存在则创建
     */
    @TenantIgnore
    private String getOrCreateDevGroupId() {
        String devGroupPath = "magic-api/api/dev/group.json";
        
        try {
            // 检查dev分组配置是否已存在
            List<MagicApiFileDO> existingDevGroup = magicApiFileMapper.selectList(null);
            
            for (MagicApiFileDO file : existingDevGroup) {
                if (devGroupPath.equals(file.getFilePath())) {
                    // 解析已存在的dev分组配置，获取其ID
                    try {
                        JSONObject devGroupJson = JSONObject.parseObject(file.getFileContent());
                        String existingId = devGroupJson.getString("id");
                        if (StrUtil.isNotEmpty(existingId)) {
                            log.info("[getOrCreateDevGroupId] 找到已存在的dev分组: {}", existingId);
                            return existingId;
                        }
                    } catch (Exception e) {
                        log.warn("[getOrCreateDevGroupId] 解析dev分组配置失败: {}", e.getMessage());
                    }
                }
            }
            
            // 如果不存在，使用固定ID（这样即使重启也能保持一致）
            log.info("[getOrCreateDevGroupId] dev分组不存在，使用固定ID: {}", DEV_GROUP_ID);
            return DEV_GROUP_ID;
            
        } catch (Exception e) {
            log.error("[getOrCreateDevGroupId] 查询dev分组失败，使用固定ID", e);
            return DEV_GROUP_ID;
        }
    }

    /**
     * 确保dev分组目录存在
     * 只有当dev分组不存在时才创建
     */
    private void ensureDevGroupExists(List<MagicApiFileDO> apiFiles, String devGroupId) {
        String devGroupPath = "magic-api/api/dev/group.json";
        String devPath = "magic-api/api/dev/";
        
        // 检查是否已存在dev分组配置
        boolean devGroupExists = false;
        try {
            List<MagicApiFileDO> existingFiles = magicApiFileMapper.selectList(null);
            for (MagicApiFileDO file : existingFiles) {
                if (devGroupPath.equals(file.getFilePath())) {
                    devGroupExists = true;
                    break;
                }
            }
        } catch (Exception e) {
            log.warn("[ensureDevGroupExists] 检查dev分组失败: {}", e.getMessage());
        }
        
        // 如果dev分组不存在，则创建
        if (!devGroupExists) {
            log.info("[ensureDevGroupExists] dev分组不存在，创建新的dev分组");
            
            // 创建dev分组对象（使用传入的ID）
            MagicApiGroup devGroup = new MagicApiGroup();
            devGroup.setCreateBy("admin");
            devGroup.setCreateTime(DateTime.now().getTime());
            devGroup.setId(devGroupId);
            devGroup.setName("dev");
            devGroup.setOptions(new String[]{});
            devGroup.setParentId("0");
            devGroup.setPath("/dev");
            devGroup.setPaths(new String[]{});
            devGroup.setProperties(new HashMap<>());
            devGroup.setType("api");
            devGroup.setUpdateTime(null);
            
            // 添加到待创建文件列表
            apiFiles.add(createApiFile(devPath, "this is directory"));
            apiFiles.add(createApiFile(devGroupPath, JSONObject.toJSONString(devGroup)));
            
            log.info("[ensureDevGroupExists] dev分组创建完成: {}", devGroupId);
        } else {
            log.info("[ensureDevGroupExists] dev分组已存在，跳过创建");
        }
    }

    /**
     * 判断是否是系统字段（需要排除的字段）
     * 同时检查下划线格式和驼峰格式
     */
    private boolean isSystemField(String fieldName) {
        return SYSTEM_FIELDS.contains(fieldName) || SYSTEM_FIELDS.contains(toCamelCase(fieldName));
    }
    
    /**
     * 判断字段是否应该在列表中显示
     * 优先级：listOperationResult > 系统字段过滤
     */
    private boolean shouldShowInList(GenericTableConfigRespVO.GenericTableColumnConfig column) {
        // 如果明确设置了listOperationResult=true，则显示该字段，即使是系统字段
        if (Boolean.TRUE.equals(column.getListOperationResult())) {
            return true;
        }
        // 如果明确设置了listOperationResult=false，则不显示
        if (Boolean.FALSE.equals(column.getListOperationResult())) {
            return false;
        }
        // 如果未设置listOperationResult，则根据是否是系统字段决定
        return !isSystemField(column.getColumnName());
    }

    /**
     * 判断字段是否应该在查询条件中显示
     */
    private boolean shouldShowInQuery(GenericTableConfigRespVO.GenericTableColumnConfig column) {
        // 如果明确设置了listOperation=true，则显示该字段，即使是系统字段
        if (Boolean.TRUE.equals(column.getListOperation())) {
            return true;
        }
        // 如果明确设置了listOperation=false，则不显示
        if (Boolean.FALSE.equals(column.getListOperation())) {
            return false;
        }
        // 如果未设置listOperation，则根据是否是系统字段决定
        return !isSystemField(column.getColumnName());
    }

    /**
     * 判断字段是否应该在新增操作中显示
     */
    private boolean shouldShowInCreate(GenericTableConfigRespVO.GenericTableColumnConfig column) {
        // 如果明确设置了createOperation=true，则显示该字段，即使是系统字段
        if (Boolean.TRUE.equals(column.getCreateOperation())) {
            return true;
        }
        // 如果明确设置了createOperation=false，则不显示
        if (Boolean.FALSE.equals(column.getCreateOperation())) {
            return false;
        }
        // 如果未设置createOperation，则根据是否是系统字段决定
        return !isSystemField(column.getColumnName());
    }

    /**
     * 判断字段是否应该在修改操作中显示
     */
    private boolean shouldShowInUpdate(GenericTableConfigRespVO.GenericTableColumnConfig column) {
        // 如果明确设置了updateOperation=true，则显示该字段，即使是系统字段
        if (Boolean.TRUE.equals(column.getUpdateOperation())) {
            return true;
        }
        // 如果明确设置了updateOperation=false，则不显示
        if (Boolean.FALSE.equals(column.getUpdateOperation())) {
            return false;
        }
        // 如果未设置updateOperation，则根据是否是系统字段决定
        return !isSystemField(column.getColumnName());
    }

    /**
     * 获取主键字段
     */
    private String getPrimaryKey(GenericTableConfigRespVO tableConfig) {
        return tableConfig.getColumns().stream()
                .filter(GenericTableConfigRespVO.GenericTableColumnConfig::getPrimaryKey)
                .map(GenericTableConfigRespVO.GenericTableColumnConfig::getField)
                .findFirst()
                .orElse("id");
    }

    /**
     * 创建插入接口
     */
    private String createInsertInterface(String groupId, String dataSourceCall, String tableName, 
                                       List<GenericTableConfigRespVO.GenericTableColumnConfig> columns) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("增加");
        apiFile.setPath("/insert");
        apiFile.setMethod("POST");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 设置参数和请求体
        apiFile.setParameters(new ArrayList<>());
        apiFile.setRequestBody(generateRequestBody(columns, false));
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateRequestBodyDefinition(columns, false));
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        // 生成插入脚本（移除日期处理逻辑避免报错）
        StringBuilder scriptBuilder = new StringBuilder();
        scriptBuilder.append("return ").append(dataSourceCall).append(".table(\"").append(tableName).append("\").insert(body);");
        String script = scriptBuilder.toString();
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建更新接口
     */
    private String createUpdateInterface(String groupId, String dataSourceCall, String tableName, 
                                       String primaryKey, List<GenericTableConfigRespVO.GenericTableColumnConfig> columns) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("修改");
        apiFile.setPath("/update");
        apiFile.setMethod("POST");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        apiFile.setParameters(new ArrayList<>());
        apiFile.setRequestBody(generateRequestBody(columns, true));
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateRequestBodyDefinition(columns, true));
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        // 生成更新脚本（移除日期处理逻辑避免报错）
        StringBuilder scriptBuilder = new StringBuilder();
        scriptBuilder.append("return ").append(dataSourceCall).append(".table(\"").append(tableName).append("\").primary(\"").append(primaryKey).append("\").update(body);");
        String script = scriptBuilder.toString();
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建逻辑删除接口
     */
    private String createLogicDeleteInterface(String groupId, String dataSourceCall, String tableName, String primaryKey) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("逻辑删");
        apiFile.setPath("/delete");
        apiFile.setMethod("GET");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 删除接口的参数
        List<MagicApiItem> params = new ArrayList<>();
        MagicApiItem idParam = new MagicApiItem();
        idParam.setName(primaryKey);
        idParam.setValue("0");
        idParam.setRequired(true);
        idParam.setDataType("String");
        idParam.setDescription("");
        idParam.setValidateType("");
        idParam.setError("");
        idParam.setExpression("");
        idParam.setChildren(new ArrayList<>());
        params.add(idParam);
        
        apiFile.setParameters(params);
        apiFile.setRequestBody("{}");
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateEmptyRequestBodyDefinition());
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        // 支持单个ID或多个ID（逗号分隔）
        String script = "if (" + primaryKey + ".indexOf(',') > -1) {\n" +
                        "    return " + dataSourceCall + ".table(\"" + tableName + "\").primary(\"" + primaryKey + "\").logic().in('" + primaryKey + "'," + primaryKey + ".split(',')).delete();\n" +
                        "} else {\n" +
                        "    return " + dataSourceCall + ".table(\"" + tableName + "\").primary(\"" + primaryKey + "\").logic().eq('" + primaryKey + "'," + primaryKey + ").delete();\n" +
                        "}";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建物理删除接口
     */
    private String createPhysicalDeleteInterface(String groupId, String dataSourceCall, String tableName, String primaryKey) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("物理删");
        apiFile.setPath("/physical-delete");
        apiFile.setMethod("GET");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 物理删除接口的参数（与逻辑删除相同）
        List<MagicApiItem> params = new ArrayList<>();
        MagicApiItem idParam = new MagicApiItem();
        idParam.setName(primaryKey);
        idParam.setValue("0");
        idParam.setRequired(true);
        idParam.setDataType("String");
        idParam.setDescription("");
        idParam.setValidateType("");
        idParam.setError("");
        idParam.setExpression("");
        idParam.setChildren(new ArrayList<>());
        params.add(idParam);
        
        apiFile.setParameters(params);
        apiFile.setRequestBody("{}");
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateEmptyRequestBodyDefinition());
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        // 物理删除脚本（不使用.logic()），支持单个ID或多个ID
        String script = "if (" + primaryKey + ".indexOf(',') > -1) {\n" +
                        "    return " + dataSourceCall + ".table(\"" + tableName + "\").primary(\"" + primaryKey + "\").in('" + primaryKey + "'," + primaryKey + ".split(',')).delete();\n" +
                        "} else {\n" +
                        "    return " + dataSourceCall + ".table(\"" + tableName + "\").primary(\"" + primaryKey + "\").eq('" + primaryKey + "'," + primaryKey + ").delete();\n" +
                        "}";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建查询接口
     */
    private String createQueryInterface(String groupId, String dataSourceCall, String tableName,
                                      List<GenericTableConfigRespVO.GenericTableColumnConfig> columns, String dataSourceName) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("查询");
        apiFile.setPath("/query");
        apiFile.setMethod("POST");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        apiFile.setParameters(new ArrayList<>());
        apiFile.setRequestBody(generateQueryRequestBody(columns));
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateQueryRequestBodyDefinition(columns));
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        String sql = generateQuerySql(tableName, columns, dataSourceName);
        String script = sql + "return " + dataSourceCall + ".select(sql)";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建分页查询接口
     */
    private String createPageInterface(String groupId, String dataSourceCall, String tableName,
                                     List<GenericTableConfigRespVO.GenericTableColumnConfig> columns, String dataSourceName) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("分页");
        apiFile.setPath("/page");
        apiFile.setMethod("POST");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 分页参数
        List<MagicApiItem> params = new ArrayList<>();
        
        MagicApiItem pageParam = new MagicApiItem();
        pageParam.setName("page");
        pageParam.setValue("1");
        pageParam.setRequired(true);
        pageParam.setDataType("Integer");
        pageParam.setDescription("");
        pageParam.setValidateType("");
        pageParam.setError("");
        pageParam.setExpression("");
        pageParam.setChildren(new ArrayList<>());
        params.add(pageParam);
        
        MagicApiItem sizeParam = new MagicApiItem();
        sizeParam.setName("size");
        sizeParam.setValue("10");
        sizeParam.setRequired(true);
        sizeParam.setDataType("Integer");
        sizeParam.setDescription("");
        sizeParam.setValidateType("");
        sizeParam.setError("");
        sizeParam.setExpression("");
        sizeParam.setChildren(new ArrayList<>());
        params.add(sizeParam);
        
        apiFile.setParameters(params);
        apiFile.setRequestBody(generateQueryRequestBody(columns));
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateQueryRequestBodyDefinition(columns));
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        String sql = generateQuerySql(tableName, columns, dataSourceName);
        String script = sql + "return " + dataSourceCall + ".page(sql)";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }



    // 其他辅助方法省略...
    
    private List<MagicApiItem> generateHeaders() {
        List<MagicApiItem> headers = new ArrayList<>();
        
        MagicApiItem authHeader = new MagicApiItem();
        authHeader.setName("Authorization");
        authHeader.setValue("Bearer test1");
        authHeader.setRequired(true);
        authHeader.setDataType("String");
        authHeader.setDescription("");
        authHeader.setValidateType("");
        authHeader.setError("");
        authHeader.setExpression("");
        authHeader.setChildren(new ArrayList<>());
        headers.add(authHeader);
        
        MagicApiItem tenantHeader = new MagicApiItem();
        tenantHeader.setName("tenant-id");
        tenantHeader.setValue("1");
        tenantHeader.setRequired(true);
        tenantHeader.setDataType("String");
        tenantHeader.setDescription("");
        tenantHeader.setValidateType("");
        tenantHeader.setError("");
        tenantHeader.setExpression("");
        tenantHeader.setChildren(new ArrayList<>());
        headers.add(tenantHeader);
        
        return headers;
    }

    private String generateStandardResponse() {
        return "{\n" +
               "    \"code\": 0,\n" +
               "    \"message\": \"success\",\n" +
               "    \"data\": null,\n" +
               "    \"timestamp\": " + DateTime.now().getTime() + ",\n" +
               "    \"executeTime\": 16\n" +
               "}";
    }

    private String generateQuerySql(String tableName, List<GenericTableConfigRespVO.GenericTableColumnConfig> columns, String dataSourceName) {
        StringBuilder sql = new StringBuilder("var sql =\"\"\"\n");
        sql.append("SELECT \n");
        
        // 生成查询字段，根据listOperationResult配置决定是否显示
        List<String> selectFields = columns.stream()
                .filter(this::shouldShowInList) // 使用新的字段显示判断逻辑
                .map(column -> {
                    // 数据库字段名（下划线格式）
                    return "  " + column.getColumnName();
                })
                .collect(Collectors.toList());
        
        sql.append(String.join(",\n", selectFields)).append("\n");
        sql.append("FROM ").append(tableName).append("\n");
        sql.append("WHERE deleted = 0\n");
        
        // 生成查询条件，只包含设置了listOperation=true的字段
        for (GenericTableConfigRespVO.GenericTableColumnConfig column : columns) {
            String dbColumnName = column.getColumnName(); // 数据库字段名（下划线格式）
            String paramName = toCamelCase(dbColumnName);  // 前端参数名（驼峰格式）
            
            // 只有设置了listOperation=true的字段才作为查询条件
            if (!Boolean.TRUE.equals(column.getListOperation())) {
                continue;
            }
            
            String jdbcType = column.getJdbcType();
            
            if (MagicApiDataTypeUtil.isDateType(jdbcType)) {
                sql.append("-- 日期型查询前端传入的为一个日期数组\n");
                sql.append("?{body.").append(paramName).append(",and (").append(dbColumnName)
                   .append(" between #{body.").append(paramName).append(".get(0)} and #{body.")
                   .append(paramName).append(".get(1)})} \n");
            } else if (MagicApiDataTypeUtil.isStringType(jdbcType)) {
                sql.append("?{body.").append(paramName).append(", and ").append(dbColumnName)
                   .append(" like concat('%',#{body.").append(paramName).append("},'%')} \n");
            } else {
                sql.append("?{body.").append(paramName).append(",and ").append(dbColumnName)
                   .append(" = #{body.").append(paramName).append("}} \n");
            }
        }
        
        sql.append("\"\"\"\n");
        return sql.toString();
    }



    private MagicApiItem generateEmptyRequestBodyDefinition() {
        MagicApiItem root = new MagicApiItem();
        root.setName("");
        root.setValue("");
        root.setDescription("");
        root.setDataType("Object");
        root.setRequired(false);
        root.setValidateType("");
        root.setError("");
        root.setExpression("");
        root.setChildren(new ArrayList<>());
        return root;
    }

    private MagicApiItem generateResponseBodyDefinition() {
        MagicApiItem root = new MagicApiItem();
        root.setName("");
        root.setValue("");
        root.setDescription("");
        root.setDataType("Object");
        root.setRequired(false);
        root.setValidateType("");
        root.setError("");
        root.setExpression("");
        
        List<MagicApiItem> children = new ArrayList<>();
        
        // code 字段
        MagicApiItem code = new MagicApiItem();
        code.setName("code");
        code.setValue("0");
        code.setDataType("Integer");
        code.setDescription("");
        code.setValidateType("");
        code.setError("");
        code.setExpression("");
        code.setRequired(false);
        code.setChildren(new ArrayList<>());
        children.add(code);
        
        // message 字段
        MagicApiItem message = new MagicApiItem();
        message.setName("message");
        message.setValue("success");
        message.setDataType("String");
        message.setDescription("");
        message.setValidateType("");
        message.setError("");
        message.setExpression("");
        message.setRequired(false);
        message.setChildren(new ArrayList<>());
        children.add(message);
        
        // data 字段
        MagicApiItem data = new MagicApiItem();
        data.setName("data");
        data.setValue("{}");
        data.setDataType("Object");
        data.setDescription("");
        data.setValidateType("");
        data.setError("");
        data.setExpression("");
        data.setRequired(false);
        data.setChildren(new ArrayList<>());
        children.add(data);
        
        // timestamp 字段
        MagicApiItem timestamp = new MagicApiItem();
        timestamp.setName("timestamp");
        timestamp.setValue(String.valueOf(DateTime.now().getTime()));
        timestamp.setDataType("Long");
        timestamp.setDescription("");
        timestamp.setValidateType("");
        timestamp.setError("");
        timestamp.setExpression("");
        timestamp.setRequired(false);
        timestamp.setChildren(new ArrayList<>());
        children.add(timestamp);
        
        // executeTime 字段
        MagicApiItem executeTime = new MagicApiItem();
        executeTime.setName("executeTime");
        executeTime.setValue("16");
        executeTime.setDataType("Integer");
        executeTime.setDescription("");
        executeTime.setValidateType("");
        executeTime.setError("");
        executeTime.setExpression("");
        executeTime.setRequired(false);
        executeTime.setChildren(new ArrayList<>());
        children.add(executeTime);
        
        root.setChildren(children);
        return root;
    }

    /**
     * 创建Excel导出接口
     */
    private String createExcelExportInterface(String groupId, String dataSourceCall, String tableName,
                                            List<GenericTableConfigRespVO.GenericTableColumnConfig> columns, String tableComment) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("导出");
        apiFile.setPath("/export");
        apiFile.setMethod("GET");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        apiFile.setParameters(new ArrayList<>());
        apiFile.setRequestBody("{}");
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(null);
        apiFile.setRequestBodyDefinition(null);
        apiFile.setResponseBodyDefinition(null);
        
        String script = generateExcelExportScript(dataSourceCall, tableName, columns, tableComment);
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 生成Excel导出脚本（去掉注释）
     */
    private String generateExcelExportScript(String dataSourceCall, String tableName,
                                           List<GenericTableConfigRespVO.GenericTableColumnConfig> columns, String tableComment) {
        StringBuilder script = new StringBuilder();
        
        script.append("import cn.hutool.poi.excel.ExcelUtil;\n");
        script.append("import response;\n");
        script.append("import java.io.ByteArrayOutputStream;\n");
        script.append("import java.text.SimpleDateFormat;\n");
        script.append("import java.util.Date;\n");
        String selectColumns = columns.stream()
                .filter(this::shouldShowInList)
                .map(col -> col.getColumnName())
                .collect(Collectors.joining(", "));
        
        script.append("var data = ").append(dataSourceCall)
                .append(".select(\"SELECT ").append(selectColumns)
                .append(" FROM ").append(tableName).append(" WHERE deleted = 0\");\n\n");
        
        script.append("var writer = ExcelUtil.getWriter();\n");
        
        // 设置中文表头
        List<GenericTableConfigRespVO.GenericTableColumnConfig> filteredColumns = columns.stream()
                .filter(this::shouldShowInList)
                .collect(Collectors.toList());
        
        for (int i = 0; i < filteredColumns.size(); i++) {
            GenericTableConfigRespVO.GenericTableColumnConfig column = filteredColumns.get(i);
            String chineseHeader = StrUtil.isNotBlank(column.getColumnComment()) ? 
                column.getColumnComment() : column.getColumnName();
            script.append("writer.addHeaderAlias(\"").append(column.getColumnName())
                  .append("\", \"").append(chineseHeader).append("\");\n");
        }
        script.append("\n");
        
        script.append("writer.write(data, true);\n\n");
        
        script.append("var bos = new ByteArrayOutputStream();\n");
        script.append("writer.flush(bos, true);\n");
        script.append("var bytes = bos.toByteArray();\n\n");
        
        script.append("writer.close();\n");
        script.append("bos.close();\n\n");
        
        script.append("var timestamp = new SimpleDateFormat(\"yyyyMMdd_HHmmss\").format(new Date());\n");
        script.append("var filename = \"").append(tableName).append("_\" + timestamp + \".xlsx\";\n");
        script.append("return response.download(bytes, filename);");
        
        return script.toString();
    }

    /**
     * 生成请求体示例（小驼峰格式）
     */
    private String generateRequestBody(List<GenericTableConfigRespVO.GenericTableColumnConfig> columns, boolean includeId) {
        StringBuilder requestBody = new StringBuilder("{\n");
        
        List<String> fields = new ArrayList<>();
        
        if (includeId) {
            fields.add("  \"id\": 1");
        }
        
        for (GenericTableConfigRespVO.GenericTableColumnConfig column : columns) {
            String dbColumnName = column.getColumnName();
            
            // 跳过主键（如果不需要包含ID）
            if (!includeId && "id".equals(dbColumnName)) {
                continue;
            }
            
            // 根据操作类型决定是否包含该字段
            boolean shouldInclude = includeId ? 
                (Boolean.TRUE.equals(column.getUpdateOperation())) : // 更新操作
                (Boolean.TRUE.equals(column.getCreateOperation())); // 创建操作
                
            if (!shouldInclude) {
                continue;
            }
            
            String paramName = toCamelCase(dbColumnName); // 转换为小驼峰
            String exampleValue = getExampleValue(column.getJdbcType());
            fields.add("  \"" + paramName + "\": " + exampleValue);
        }
        
        requestBody.append(String.join(",\n", fields));
        requestBody.append("\n}");
        
        return requestBody.toString();
    }

    /**
     * 生成查询请求体示例（小驼峰格式）
     */
    private String generateQueryRequestBody(List<GenericTableConfigRespVO.GenericTableColumnConfig> columns) {
        StringBuilder requestBody = new StringBuilder("{\n");
        
        List<String> fields = new ArrayList<>();
        
        for (GenericTableConfigRespVO.GenericTableColumnConfig column : columns) {
            String dbColumnName = column.getColumnName();
            
            // 跳过不需要在查询条件中显示的字段
            if (!shouldShowInQuery(column)) {
                continue;
            }
            
            String paramName = toCamelCase(dbColumnName); // 转换为小驼峰
            String exampleValue = getExampleValue(column.getJdbcType());
            fields.add("  \"" + paramName + "\": " + exampleValue);
        }
        
        requestBody.append(String.join(",\n", fields));
        requestBody.append("\n}");
        
        return requestBody.toString();
    }

    /**
     * 生成请求体定义（小驼峰格式）
     */
    private MagicApiItem generateRequestBodyDefinition(List<GenericTableConfigRespVO.GenericTableColumnConfig> columns, boolean includeId) {
        MagicApiItem root = new MagicApiItem();
        root.setName("");
        root.setValue("");
        root.setDescription("");
        root.setDataType("Object");
        root.setRequired(false);
        root.setValidateType("");
        root.setError("");
        root.setExpression("");
        
        List<MagicApiItem> children = new ArrayList<>();
        
        if (includeId) {
            MagicApiItem idItem = new MagicApiItem();
            idItem.setName("id");
            idItem.setValue("1");
            idItem.setDataType("Long");
            idItem.setDescription("主键ID");
            idItem.setRequired(true);
            idItem.setValidateType("");
            idItem.setError("");
            idItem.setExpression("");
            idItem.setChildren(new ArrayList<>());
            children.add(idItem);
        }
        
        for (GenericTableConfigRespVO.GenericTableColumnConfig column : columns) {
            String dbColumnName = column.getColumnName();
            
            // 跳过主键（如果不需要包含ID）
            if (!includeId && "id".equals(dbColumnName)) {
                continue;
            }
            
            // 根据配置决定是否显示字段
            if (includeId) {
                // 修改操作，使用updateOperation配置
                if (!shouldShowInUpdate(column)) {
                    continue;
                }
            } else {
                // 新增操作，使用createOperation配置
                if (!shouldShowInCreate(column)) {
                    continue;
                }
            }
            
            MagicApiItem item = new MagicApiItem();
            item.setName(toCamelCase(dbColumnName)); // 使用小驼峰格式
            item.setValue(getExampleValue(column.getJdbcType()));
            item.setDataType(convertJdbcTypeToApiType(column.getJdbcType()));
            item.setDescription(column.getColumnComment());
            item.setRequired(false);
            item.setValidateType("");
            item.setError("");
            item.setExpression("");
            item.setChildren(new ArrayList<>());
            children.add(item);
        }
        
        root.setChildren(children);
        return root;
    }

    /**
     * 生成查询请求体定义（小驼峰格式）
     */
    private MagicApiItem generateQueryRequestBodyDefinition(List<GenericTableConfigRespVO.GenericTableColumnConfig> columns) {
        MagicApiItem root = new MagicApiItem();
        root.setName("");
        root.setValue("");
        root.setDescription("");
        root.setDataType("Object");
        root.setRequired(false);
        root.setValidateType("");
        root.setError("");
        root.setExpression("");
        
        List<MagicApiItem> children = new ArrayList<>();
        
        for (GenericTableConfigRespVO.GenericTableColumnConfig column : columns) {
            String dbColumnName = column.getColumnName();
            
            // 跳过不需要在查询条件中显示的字段
            if (!shouldShowInQuery(column)) {
                continue;
            }
            
            MagicApiItem item = new MagicApiItem();
            item.setName(toCamelCase(dbColumnName)); // 使用小驼峰格式
            item.setValue(getExampleValue(column.getJdbcType()));
            item.setDataType(convertJdbcTypeToApiType(column.getJdbcType()));
            item.setDescription(column.getColumnComment() + "（查询条件）");
            item.setRequired(false);
            item.setValidateType("");
            item.setError("");
            item.setExpression("");
            item.setChildren(new ArrayList<>());
            children.add(item);
        }
        
        root.setChildren(children);
        return root;
    }

    /**
     * 根据JDBC类型获取示例值
     */
    private String getExampleValue(String jdbcType) {
        if (MagicApiDataTypeUtil.isStringType(jdbcType)) {
            return "\"示例\"";
        } else if (MagicApiDataTypeUtil.isDateType(jdbcType)) {
            return "\"2023-01-01\"";
        } else if ("BIGINT".equalsIgnoreCase(jdbcType) || "INTEGER".equalsIgnoreCase(jdbcType)) {
            return "1";
        } else if ("DECIMAL".equalsIgnoreCase(jdbcType) || "DOUBLE".equalsIgnoreCase(jdbcType)) {
            return "0.00";
        } else {
            return "\"\"";
        }
    }

    /**
     * 转换JDBC类型为API类型
     */
    private String convertJdbcTypeToApiType(String jdbcType) {
        if (MagicApiDataTypeUtil.isStringType(jdbcType)) {
            return "String";
        } else if (MagicApiDataTypeUtil.isDateType(jdbcType)) {
            return "String";
        } else if ("BIGINT".equalsIgnoreCase(jdbcType)) {
            return "Long";
        } else if ("INTEGER".equalsIgnoreCase(jdbcType)) {
            return "Integer";
        } else if ("DECIMAL".equalsIgnoreCase(jdbcType) || "DOUBLE".equalsIgnoreCase(jdbcType)) {
            return "Double";
        } else {
            return "String";
        }
    }

    /**
     * 创建单个ID逻辑删除接口
     */
    private String createSingleLogicDeleteInterface(String groupId, String dataSourceCall, String tableName, String primaryKey) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("删除");
        apiFile.setPath("/delete");
        apiFile.setMethod("GET");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 单个ID参数
        List<MagicApiItem> params = new ArrayList<>();
        MagicApiItem idParam = new MagicApiItem();
        idParam.setName(primaryKey);
        idParam.setValue("1");
        idParam.setRequired(true);
        idParam.setDataType("Long");
        idParam.setDescription("");
        idParam.setValidateType("");
        idParam.setError("");
        idParam.setExpression("");
        idParam.setChildren(new ArrayList<>());
        params.add(idParam);
        
        apiFile.setParameters(params);
        apiFile.setRequestBody("{}");
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateEmptyRequestBodyDefinition());
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        String script = "return " + dataSourceCall + ".table(\"" + tableName + "\")\n" +
                        "        .logic()\n" +
                        "        .where()\n" +
                        "        .eq('" + primaryKey + "', " + primaryKey + ")\n" +
                        "        .delete()";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建批量逻辑删除接口
     */
    private String createBatchLogicDeleteInterface(String groupId, String dataSourceCall, String tableName, String primaryKey) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("批量删除");
        apiFile.setPath("/batch-delete");
        apiFile.setMethod("GET");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 批量ID参数（逗号分隔）
        List<MagicApiItem> params = new ArrayList<>();
        MagicApiItem idsParam = new MagicApiItem();
        idsParam.setName("ids");
        idsParam.setValue("1,2,3");
        idsParam.setRequired(true);
        idsParam.setDataType("String");
        idsParam.setDescription("多个ID用逗号分隔");
        idsParam.setValidateType("");
        idsParam.setError("");
        idsParam.setExpression("");
        idsParam.setChildren(new ArrayList<>());
        params.add(idsParam);
        
        apiFile.setParameters(params);
        apiFile.setRequestBody("{}");
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateEmptyRequestBodyDefinition());
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        String script = "return " + dataSourceCall + ".table(\"" + tableName + "\")\n" +
                        "        .logic()\n" +
                        "        .where()\n" +
                        "        .in('" + primaryKey + "', ids.split(','))\n" +
                        "        .delete()";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建单个ID物理删除接口
     */
    private String createSinglePhysicalDeleteInterface(String groupId, String dataSourceCall, String tableName, String primaryKey) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("物理删除");
        apiFile.setPath("/physical-delete");
        apiFile.setMethod("GET");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 单个ID参数
        List<MagicApiItem> params = new ArrayList<>();
        MagicApiItem idParam = new MagicApiItem();
        idParam.setName(primaryKey);
        idParam.setValue("1");
        idParam.setRequired(true);
        idParam.setDataType("Long");
        idParam.setDescription("");
        idParam.setValidateType("");
        idParam.setError("");
        idParam.setExpression("");
        idParam.setChildren(new ArrayList<>());
        params.add(idParam);
        
        apiFile.setParameters(params);
        apiFile.setRequestBody("{}");
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateEmptyRequestBodyDefinition());
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        String script = "return " + dataSourceCall + ".table(\"" + tableName + "\")\n" +
                        "        .where()\n" +
                        "        .eq('" + primaryKey + "', " + primaryKey + ")\n" +
                        "        .delete()";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }

    /**
     * 创建批量物理删除接口
     */
    private String createBatchPhysicalDeleteInterface(String groupId, String dataSourceCall, String tableName, String primaryKey) {
        MagicApiFile apiFile = new MagicApiFile();
        apiFile.setId(IdUtil.simpleUUID());
        apiFile.setGroupId(groupId);
        apiFile.setName("批量物理删除");
        apiFile.setPath("/batch-physical-delete");
        apiFile.setMethod("GET");
        apiFile.setCreateBy("system");
        apiFile.setCreateTime(DateTime.now().getTime());
        apiFile.setUpdateTime(DateTime.now().getTime());
        apiFile.setProperties(new Object());
        
        // 批量ID参数（逗号分隔）
        List<MagicApiItem> params = new ArrayList<>();
        MagicApiItem idsParam = new MagicApiItem();
        idsParam.setName("ids");
        idsParam.setValue("1,2,3");
        idsParam.setRequired(true);
        idsParam.setDataType("String");
        idsParam.setDescription("多个ID用逗号分隔");
        idsParam.setValidateType("");
        idsParam.setError("");
        idsParam.setExpression("");
        idsParam.setChildren(new ArrayList<>());
        params.add(idsParam);
        
        apiFile.setParameters(params);
        apiFile.setRequestBody("{}");
        apiFile.setHeaders(generateHeaders());
        apiFile.setOptions(new String[]{});
        apiFile.setPaths(new String[]{});
        apiFile.setResponseBody(generateStandardResponse());
        apiFile.setRequestBodyDefinition(generateEmptyRequestBodyDefinition());
        apiFile.setResponseBodyDefinition(generateResponseBodyDefinition());
        
        String script = "return " + dataSourceCall + ".table(\"" + tableName + "\")\n" +
                        "        .where()\n" +
                        "        .in('" + primaryKey + "', ids.split(','))\n" +
                        "        .delete()";
        
        return JSONObject.toJSONString(apiFile) + "\n================================\n" + script;
    }
}